package com.a3dweijing.wetouch2.fragment;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Activity.GoodsListViewActivity;
import com.a3dweijing.wetouch2.Activity.ShoppingDetailsActivity;
import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.GaoDeMap;
import com.a3dweijing.wetouch2.Util.PermissionapplicationHelp;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.adapter.ShoppingHomeAdapter;
import com.a3dweijing.wetouch2.bean.ShoppingHome;
import com.a3dweijing.wetouch2.constant.Api;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.content.pm.PackageManager.PERMISSION_GRANTED;

/**
 * Created by Administrator on 2018/3/20. 购物
 */

public class ShoppingCartFragment extends Fragment
{
    @BindView(R.id.back)
    TextView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    Unbinder unbinder;
    
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    
    @BindView(R.id.loading_date)
    LinearLayout loadingDate;
    
    @BindView(R.id.resaut_status)
    LinearLayout resautStatus;
    
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    
    private View view;
    
    private GridLayoutManager layout;
    
    private ArrayList<Object> objects;
    
    private Gson gson;
    
    private ShoppingHomeAdapter adapter;
    
    private AMapLocationClient aMapLocationClient;
    
    // 首页展示信息
    private ShoppingHome shoppingHome;
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState)
    {
        if (view != null)
            return view;
        view = LayoutInflater.from(getContext()).inflate(R.layout.shopping_cart_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        initTopView();
        initView();
        initDate(true);
        initMap();
        setOnClick();
        return view;
    }
    
    private void setOnClick()
    {
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                initDate(false);
            }
        });
    }
    
    private void initMap()
    {
        String[] strings = new String[] {Manifest.permission.ACCESS_COARSE_LOCATION};
        int permissionapplication = PermissionapplicationHelp.Permissionapplication(this, strings[0], strings);
        if (permissionapplication == PERMISSION_GRANTED)
        {
            GaoDeMap map = new GaoDeMap();
            aMapLocationClient = map.createMap(callBack);
        }
    }
    
    /**
     * 定位的回调
     */
    CallBack callBack = new CallBack()
    {
        @Override
        public void doNext(int what, Object obj)
        {
            if (what == 0)
            {
                Singleton.getInstance().setLocation((AMapLocation)obj);
                back.setText(((AMapLocation)obj).getCity());
            }
            else if (what == -1 && obj != null)
            {
                Toast.makeText(getActivity(), ((AMapLocation)obj).getErrorInfo(), Toast.LENGTH_SHORT).show();
            }
        }
    };
    
    /**
     * view监听的回调
     */
    CallBack onlick = new CallBack()
    {
        @Override
        public void doNext(int what, Object obj)
        {
            switch (what)
            {
                case R.id.text_more:
                    GoodsListViewActivity.startActivity(getActivity(), -1, "全部商品");
                    break;
                case R.id.shopping_cen_img:
                    if (shoppingHome.getBigPictureRecommend() != null
                        && shoppingHome.getBigPictureRecommend().size() > 0)
                    {
                        List<ShoppingHome.BigPictureRecommendBean> bigPictureRecommend =
                            shoppingHome.getBigPictureRecommend();
                        int s_goods_id = bigPictureRecommend.get(0).getS_goods_id();
                        ShoppingDetailsActivity.startActivity(getActivity(), s_goods_id);
                    }
                    break;
                case R.id.rl_item_shopping:
                    if (obj != null && obj instanceof ShoppingHome.HomeRecommendBean)
                    {
                        ShoppingHome.HomeRecommendBean bean = (ShoppingHome.HomeRecommendBean)obj;
                        int s_goods_id = bean.getS_goods_id();
                        ShoppingDetailsActivity.startActivity(getActivity(), s_goods_id);
                    }
                    break;
                case R.id.rl_baojianping:
                    ShoppingHome.ClassifyBean classifyBean = shoppingHome.getClassify().get(0);
                    GoodsListViewActivity.startActivity(getActivity(),
                        classifyBean.getGoods_type_id(),
                        classifyBean.getGoods_type_name());
                    break;
                case R.id.rl_jiankangshiping:
                    ShoppingHome.ClassifyBean classifyBean2 = shoppingHome.getClassify().get(1);
                    GoodsListViewActivity.startActivity(getActivity(),
                        classifyBean2.getGoods_type_id(),
                        classifyBean2.getGoods_type_name());
                    break;
                case R.id.jiankangjixie:
                    ShoppingHome.ClassifyBean classifyBean3 = shoppingHome.getClassify().get(2);
                    GoodsListViewActivity.startActivity(getActivity(),
                        classifyBean3.getGoods_type_id(),
                        classifyBean3.getGoods_type_name());
                    break;
                case R.id.jiankangtuangou_rl:
                    ShoppingHome.ClassifyBean classifyBean4 = shoppingHome.getClassify().get(3);
                    GoodsListViewActivity.startActivity(getActivity(),
                            classifyBean4.getGoods_type_id(),
                            classifyBean4.getGoods_type_name());
                    break;
            }
        }
    };
    
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length > 0 && permissions[0].equals(Manifest.permission.ACCESS_COARSE_LOCATION)
            && grantResults[0] == PERMISSION_GRANTED)
        {
            GaoDeMap map = new GaoDeMap();
            aMapLocationClient = map.createMap(callBack);
        }
    }
    
    private void initDate(boolean isView)
    {
        if (isView)
        {
            loadingDate.setVisibility(View.VISIBLE);
        }
        resautStatus.setVisibility(View.GONE);
        Api api = RetrofitUtil.getInstance().getApiOfPhp();
        Call<JsonObject> c = api.shoppingHome();
        c.enqueue(new Callback<JsonObject>()
        {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response)
            {
                swipeRefreshLayout.setRefreshing(false);
                loadingDate.setVisibility(View.GONE);
                JsonObject body = response.body();
                if (body != null)
                {
                    gson = new Gson();
                    shoppingHome = gson.fromJson(body, ShoppingHome.class);
                    if (shoppingHome.isFlag())
                    {
                        resautStatus.setVisibility(View.GONE);
                        objects.clear();
                        objects.add(shoppingHome.getBanner());
                        objects.add(shoppingHome.getClassify());
                        objects.add(shoppingHome.getBigPictureRecommend());
                        for (ShoppingHome.HomeRecommendBean homeRecommendBean : shoppingHome.getHomeRecommend())
                        {
                            objects.add(homeRecommendBean);
                        }
                        adapter.notifyDataSetChanged();
                        
                    }
                }
                else
                    resautStatus.setVisibility(View.VISIBLE);
            }
            
            @Override
            public void onFailure(Call<JsonObject> call, Throwable t)
            {
                loadingDate.setVisibility(View.GONE);
                resautStatus.setVisibility(View.VISIBLE);
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
    
    private void initView()
    {
        layout = new GridLayoutManager(getActivity(), 2);
        recyclerView.setLayoutManager(layout);
        layout.setSpanSizeLookup(new CustomSpanSizeLookUp(layout));
        if (adapter == null)
        {
            objects = new ArrayList<>();
            adapter = new ShoppingHomeAdapter(getContext(), objects);
            adapter.setOnClick(onlick);
            recyclerView.setAdapter(adapter);
        }
    }
    
    private void initTopView()
    {
        topAll.setBackgroundResource(R.color.white);
        topText.setText("ANGA商城");
        topText.setTextColor(getResources().getColor(R.color.black));
    }
    
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        unbinder.unbind();
        if (aMapLocationClient != null)
        {
            aMapLocationClient.stopLocation();// 停止定位后，本地定位服务并不会被销毁
            aMapLocationClient.onDestroy();// 销毁定位客户端，同时销毁本地定位服务。
        }
    }
    
    @Override
    public void onDestroyView()
    {
        super.onDestroyView();
    }
    
    /**
     * 自定义GridLayoutManager的item占比显示
     */
    class CustomSpanSizeLookUp extends GridLayoutManager.SpanSizeLookup
    {
        
        GridLayoutManager c;
        
        public CustomSpanSizeLookUp(GridLayoutManager c)
        {
            this.c = c;
        }
        
        @Override
        public int getSpanSize(int position)
        {
            if (position <= 2)
                return c.getSpanCount();
            else
                return 1;
        }
    }
}
